﻿using FinalPointSet.Model.Constant;
using System.Collections.Generic;

namespace FinalPointSet.Model.Manager
{
    public class MessageManager
    {
        public delegate void BroadcastHanlder(MsgArg arg);
        private static readonly Dictionary<MsgType, Dictionary<int, BroadcastHanlder>> broadcastHanlderDict = new();
        /// <summary>
        /// 消息委托的自增ID
        /// </summary>
        private static int indexID = 0;
        /// <summary>
        /// 监听消息
        /// </summary>
        /// <param name="msgType">消息类型</param>
        /// <param name="onBroadcast">委托方法</param>
        /// <returns></returns>
        public static int Listening(MsgType msgType, BroadcastHanlder onBroadcast)
        {
            broadcastHanlderDict.TryGetValue(msgType, out var broadcastHanlders);
            if (broadcastHanlders != null)
            {
                broadcastHanlders.Add(indexID, onBroadcast);
            }
            else
            {
                broadcastHanlders = new()
                {
                    {indexID, onBroadcast}
                };
                broadcastHanlderDict.Add(msgType, broadcastHanlders);
            }

            return indexID++;
        }

        /// <summary>
        /// 取消监听
        /// </summary>
        /// <param name="msgType">监听类型</param>
        /// <param name="indexID">监听ID</param>

        public static void CancelListening(MsgType msgType, int indexID)
        {
            broadcastHanlderDict.TryGetValue(msgType, out var broadcastHanlders);
            broadcastHanlders?.Remove(indexID);
        }

        /// <summary>
        /// 广播
        /// </summary>
        /// <param name="msgType">消息类型</param>
        /// <param name="msgArg">消息体</param>
        public static void Broadcast(MsgType msgType, MsgArg msgArg)
        {
            broadcastHanlderDict.TryGetValue(msgType, out var broadcastHanlders);
            if (broadcastHanlders != null)
            {
                foreach (var entry in broadcastHanlders)
                {
                    entry.Value?.Invoke(msgArg);
                }
            }
        }
    }
    /// <summary>
    /// 消息参数
    /// </summary>
    public class MsgArg
    {
        /// <summary>
        /// 键
        /// </summary>
        public int Key { get; set; } = -1;
        /// <summary>
        /// 值
        /// </summary>
        public string Value { get; set; } = string.Empty;
        public MsgArg() { }
        public MsgArg(int key, string value) { Key = key; Value = value; }
        public override string ToString() { return Value; }
    }

    /// <summary>
    /// 弹窗消息参数
    /// </summary>
    public class GrowMsgArg : MsgArg
    {
        /// <summary>
        /// 窗体类型
        /// </summary>
        public string WindowType { get; set; } = string.Empty;

        public GrowMsgArg(string windowType, int key, string value) : base(key, value)
        {
            WindowType = windowType;
        }
    }
}
